<template>
    <div class="liveRoom">
        <div class="container-self">
            <!--房间头部-->
            <div class="roomHearder">
                <!--用户头像-->
                <div class="userAvatar">
                    <el-avatar  :size="70" style="cursor:pointer;"
                               :src="img.m_url"></el-avatar>
                </div>
                <!--房间标题-->
                <div class="roomTitle">
                    <div>
                        <h4 class="room-title">aaa</h4>
                        <div class="room-user">
                            主播：zhangsan
                            <el-tag type="info" size="small" effect="dark">未开播</el-tag>
                        </div>
                    </div>
                    <el-button v-if="host"  type="danger" size="small" style="height: 35px">下播</el-button>
                </div>
                <div class="clearFix"></div>
            </div>
            <!--直播内容-->
            <div class="content">
                <!--直播屏幕-->
                <!--主播-->
                <div class="screenContent" v-if="host">
                    <!--弹幕-->
                    <div class="barrage">
                        <ul v-for="(item,index) in barrage" :key="index">
                            <li class="barrageLi" ref="barrageInfo">{{item}}</li>
                        </ul>
                    </div>
                    <agora-video
                        v-if="localStream"
                        :stream="localStream"
                        :domId="localStream.getId()"
                    ></agora-video>
                </div>
                <!--观众屏幕-->
                <div class="screenContent" v-else>
                    <!--弹幕-->
                    <div class="barrage">
                        <ul v-for="(item,index) in barrage" :key="index">
                            <li class="barrageLi" ref="barrageInfo">{{item}}</li>
                        </ul>
                    </div>
                    <agora-video
                        v-if="stream"
                        :stream="stream"
                        :domId="stream.getId()"
                        :isSub="true"
                    ></agora-video>
                </div>
                <!--聊天框-->
                <div class="chat">
                    <!--聊天屏幕-->
                    <div class="chatScreen" ref="chatScreen">
                        <ul v-for="(item,i) in chatScreenLive" :key="i">
                            <li ref="chatli">{{item}}</li>
                        </ul>
                    </div>
                    <!--聊天输入框-->
                    <div class="chatInput">
                        <el-input v-if="userInfo.username" placeholder="开始聊天吧~" maxlength="25" show-word-limit
                                  v-model="chatInfo" class="input-with-select" ref="input"
                                  :disabled="sendInterval">
                            <el-button slot="append">发送</el-button>
                        </el-input>
                        <el-input v-else placeholder="请先登录噢~" class="input-with-select" disabled>
                        </el-input>
                    </div>
                </div>
                <div class="clearFix"></div>
            </div>
        </div>
    </div>
</template>
<script>
import AgoraRTC from 'agora-rtc-sdk'
import AgoraRTM from 'agora-rtm-sdk'
import {roomDetail,agoraToken} from '@/api/train.js'
import { mapState } from "vuex";
//设置直播参数
var rtc = {
    client: null,
    joined: false,
    published: false,
    localStream: null,
    remoteStreams: [],
    params: {}
};
//设置个人参数(默认)
var option = {
    appID: "074652e33cac4f62bc91dff0b8ff06dd",
    channel: "TextChannelName",
    uid: null,
    token: null
};
//聊天室配置
var rtm = {
    client: null,
    channel: null,
}


export default {
    name: "liveRoom",
    data() {
        return {
            //发送的消息框内容
            chatInfo: '',
            domId:0,
            stream:null,
            localStream:null,
            //聊天内容总览
            chatScreenLive: [],
            screenLoading: true,
            sendInterval: false,
            //循环清弹幕
            displayInertval: '',
            //循环清除聊天池
            clearChatInfo: '',
            //弹幕
            barrage: [],
            host:null,//判断是否为主播
            isLive: 0, //判断是否已开播
            room:{}
        }
    },
    computed: {
        ...mapState('UM', ['userInfo'])
      },
      components: {
            'agora-video': resolve => { require(['./components/videoLive.vue'], resolve) },
        },
    mounted() {
        this.getDetail(this.$route.params.id)
    },
    methods: {
        // 获取直播间详情
        getDetail (id) {
            roomDetail({roomId:id}).then((res)=>{
                console.log(res,'res-detial')
                this.room = res.data;
                option.channel = res.data.liveRoom;
                option.uid = this.userInfo.userId || null;
                if(this.room.createUser==this.userInfo.userId){
                    this.host=true                   
                }
                this.getToken()    
            })
        },
        getToken(){ 
            let params = {
                channelName: option.channel,
                role: this.host ? 1 : 2 // 1：主播，2：观众
            }
            if (option.uid) {
                params.userId = option.uid
            }
            // 获取声网加入频道所需token
            agoraToken(params).then((res) => {
                option.token = res.data
                if(this.host){ 
                    this.createHostLive()
                    // this.loginInChat()
                }else{
                    this.createAudLive()
                    // this.loginInChat()
                }
            }).catch(() => {
                
            })
        },
        //============主播创建直播客户端=============
        createHostLive() {
            let _this = this;
            //直播互动，建议模式为live,若为通信则为rtc
            rtc.client = AgoraRTC.createClient({mode: "live", codec: "vp8"});
            //初始化
            rtc.client.init(option.appID, function () {
                console.log("客户端初始化完成");
                //设置角色=>"host"为主播,"audience"为观众
                rtc.client.setClientRole("host");
                //=======加入频道=======
                rtc.client.join(option.token, option.channel, _this.userInfo.username, function (uid) {
                    _this.$message.success("创建成功，欢迎您，" + _this.userInfo.name);
                    rtc.params.uid = uid;
                    //角色为主播，发布本地流
                    rtc.localStream = AgoraRTC.createStream({
                        streamID: rtc.params.uid,
                        audio: true,
                        video: true,
                        screen: false,
                    });
                    //角色为主播，初始化本地流
                    rtc.localStream.init(function () {
                        // rtc.localStream.play('localStream');
                        _this.localStream=rtc.localStream
                        console.log("初始化本地流成功！");
                        _this.screenLoading = false;
                        //发布
                        rtc.client.publish(rtc.localStream, function (err) {
                            _this.$message.error("发布本地流失败！");
                            console.error(err);
                        })
                    }, function (err) {
                        //检查是否有摄像头、麦
                        _this.$message.error("初始化本地流失败，请检查摄像头和麦是否正常！")
                        console.error("init local stream failed ", err);
                    })
                }, function (err) {
                    _this.$message.error("加入频道失败" + err);
                    console.log(err)
                })
            }, (err) => {
                this.$message.error("直播间初始化失败，请检查授权码是否正确");
                console.error(err);
            });
        },
        //============观众加入直播间=================
        createAudLive() {
            let _this = this;
            //直播互动，建议模式为live,若为通信则为rtc
            rtc.client = AgoraRTC.createClient({mode: "live", codec: "vp8"});
            //初始化
            rtc.client.init(option.appID, function () {
                console.log("客户端初始化完成");
                //设置角色=>"host"为主播,"audience"为观众
                rtc.client.setClientRole("audience");
                //加入频道
                rtc.client.join(option.token, option.channel, option.uid, function (uid) {
                    if (!_this.userInfo.username) {
                        _this.$message.success("加入频道成功，欢迎您，" + uid);
                    } else {
                        _this.$message.success("加入频道成功，欢迎您，" + _this.userInfo.username);
                    }
                    rtc.params.uid = uid;
                    //监听远程流
                    rtc.client.on("stream-added", function (evt) {
                        console.log("++++++++++监听到主播流")
                        var remoteStream = evt.stream;
                        var id = remoteStream.getId();
                        rtc.client.subscribe(remoteStream, { video: true, audio: true });
                        if (id !== rtc.params.uid) {
                            rtc.client.subscribe(remoteStream, function (err) {
                                _this.$message.error("监听远程流失败" + err)
                            })
                        }
                    });
                    //监听远程订阅流
                    rtc.client.on("stream-subscribed", function (evt) {
                        console.log("++++++++++订阅主播流")
                        var remoteStream = evt.stream;
                        let id = remoteStream.getId();
                        console.log( remoteStream.getId(),' remoteStream.getId()')
                        _this.domId=id
                        _this.stream=remoteStream
                    })
                }, function (err) {
                    console.log(option.token,'option.token')
                    _this.$message.error("加入频道失败" + err);
                    console.log("加入频道失败" +err)
                })
            }, (err) => {
                this.$message.error(err);
                console.error(err);
            });

        },
        //离开直播间
        leaveLive() {
            rtc.client.leave(function () {
                rtc.localStream.stop();
                rtc.localStream.close();
                while (rtc.remoteStreams.length > 0) {
                    var stream = rtc.remoteStreams.shift();
                    var id = stream.getId();
                    stream.stop();
                    removeView(id);
                }
                console.log("离开频道成功");
            }, function (err) {
                console.log("离开频道失败" + err);
            })
        },
        //下播
        cutLive() {
            let _this = this;
            rtc.client.leave(function () {
                rtc.localStream.stop();
                rtc.localStream.close();
                while (rtc.remoteStreams.length > 0) {
                    var stream = rtc.remoteStreams.shift();
                    var id = stream.getId();
                    stream.stop();
                    removeView(id);
                }
                allUrls.updateHostInfo({
                    isLive: 0, //0为下播，1为开播
                    username: _this.hostInfo.username
                }, 'post').then(res => {
                    return res.json();
                }).then(res => {
                    if (+res.status === 200) {
                        console.log("离开频道成功");
                        _this.$message.info('下播成功~');
                    } else {
                        _this.$message.error("未能正常下播，请联系管理员");
                    }
                }).catch(err => {
                    console.log(err);
                    _this.$message.error("未能正常下播，请联系管理员");
                })
                _this.$router.push({path: '/personalCenter', query: {name: _this.userInfo.name}})
            }, function (err) {
                console.log("离开频道失败" + err);
            })
        },
        //获取用户类型，判断开播设置
        getUserType() {
            let _userType = this.$route.query.userType;
            if (_userType == 'host') {
                this.userInfo.userType = 'host';
                return new Promise(resolve => {
                    //获取主播appid
                    allUrls.getAppid({
                        username: this.hostInfo.username,
                    }, 'post').then(res => {
                        return res.json();
                    }).then(res => {
                        if (+res.status === 200) {
                            this.hostInfo.appid = res.data.appid;
                            this.userInfo.appid = res.data.appid;
                            resolve();
                        } else {
                            this.$message.error("获取appid失败！");
                        }
                    }).catch(err => {
                        console.log(err);
                        this.$message.error("获取appid出现错误");
                    })
                }).then(() => {
                    if (!this.userInfo.appid) {
                        this.$message.warning("你暂未申请直播授权码，还不可以直播哦");
                        this.$router.go(-1);
                        return false;
                    } else {
                        if (!this.hostInfo.title) {
                            this.$message.warning("你还没填写直播间信息，请填写再开播哦");
                            this.$router.go(-1)
                        } else {
                            // 主播创建直播间
                            this.createHostLive();
                            this.loginInChat();
                        }
                    }
                });
            } else {
                this.userInfo.userType = 'audience';
                //    观众方式加入直播间
                this.createAudLive();
                this.loginInChat()
            }
        },
        //登录聊天频道
        loginInChat() {
            rtm.client = AgoraRTM.createInstance(option.appID);
            //监听状态
            rtm.client.on('ConnectionStateChanged', (newState, reason) => {
                console.log('on connection state changed to ' + newState + ' reason: ' + reason);
            });
            //登录聊天频道
            rtm.client.login({token: option.token, uid: this.userInfo.username}).then(() => {
                rtm.channel = rtm.client.createChannel(option.appID);
                rtm.channel.join().then(() => {
                    /* 加入频道成功的处理逻辑 */
                    this.$message.success("成功加入聊天室");
                    //监听聊天室
                    rtm.channel.on('ChannelMessage', ({text}, senderId) => { // text 为收到的频道消息文本，senderId 为发送方的 User ID
                        /* 收到频道消息的处理逻辑 */
                        console.log("接收到远程发送的消息");
                        this.chatScreenLive.push(senderId + '：' + text);
                        this.barrage.push(text);
                    });
                }).catch(error => {
                    /* 加入频道失败的处理逻辑 */
                    this.$message.error("加入聊天室失败")
                });

            }).catch(err => {
                console.log('登录至聊天室失败', err);
            });
        },
        //发送聊天信息
        sendMsg() {
            if (this.chatInfo == '') {
                this.$message.warning("不可发送空消息哦~");
                return false;
            } else {
                rtm.channel.sendMessage({text: this.chatInfo}).then(() => {
                    /* 频道消息发送成功的处理逻辑 */
                    this.chatInfo = '';
                    //限制发送间隔时间
                    this.sendInterval = true;
                    this.$nextTick(() => {
                        setTimeout(() => {
                            this.sendInterval = false;
                        }, 1000);
                    });

                }).catch(error => {
                    /* 频道消息发送失败的处理逻辑 */
                    console.log("发送消息失败" + error)
                });
                this.chatScreenLive.push(this.userInfo.username + '：' + this.chatInfo);
                this.barrage.push(this.chatInfo);
            }
        },
        //定时清除聊天池
        clearChatinfo() {
            this.chatScreenLive.clean();
        },
        //获取是否开播状态
        getIsLiveStatus() {
            allUrls.getLiveStatus({
                username: this.hostInfo.username,
            }, 'post').then(res => {
                return res.json();
            }).then(res => {
                if (+res.status === 200) {
                    this.isLive = res.data.isLive;
                } else {
                    this.$message.error(res.desc);
                }
            }).catch(err => {
                console.log(err);
                this.$message.error("获取直播状态出错！");
            })
        },
    },
    beforeDestroy() {
        this.leaveLive()
    }
}
</script>
<style scoped lang="scss">
    @import "liveRoom";
</style>
